//
//  HomeViewController.m
//  OrderAssistant
//
//  Created by chendong on 2020/8/26.
//  Copyright © 2020 chendong. All rights reserved.
//

#import "HomeViewController.h"
#import "OrderHistoryViewController.h"
#import "MaterialViewController.h"
#import <SVProgressHUD.h>
#import <AudioToolbox/AudioToolbox.h>
#import "ReviewOfTheOrderViewController.h"
#import <AFNetworking.h>
#import "FCUUID.h"
@interface HomeViewController ()
@property(nonatomic,strong)UIButton *lastBtn;
@property(nonatomic,strong)NSDictionary *houseDic;
@property(nonatomic,strong)UIScrollView *bigBGV;
@property(nonatomic,strong)NSMutableArray *numdataArr;
@end

@implementation HomeViewController
-(NSMutableArray *)numdataArr{
    if (!_numdataArr) {
        _numdataArr = [[NSMutableArray alloc]init];
    }
    return _numdataArr;
}
-(NSDictionary *)houseDic{
    if (!_houseDic) {
        _houseDic = [[NSDictionary alloc]init];
    }
    return _houseDic;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    self.navigationController.navigationBar.barTintColor = RGBCOLOR(234, 234, 234);
    UIColor* color = [UIColor blackColor];
    NSDictionary* dict=[NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];
    self.navigationController.navigationBar.titleTextAttributes= dict;
    self.navigationItem.title = [NSString stringWithFormat:@"%@",self.dataDic[@"OrganizationName"]];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"退出" style:UIBarButtonItemStylePlain target:self action:@selector(rightAction:)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:[NSString stringWithFormat:@"%@",self.dataDic[@"UserName"]] style:UIBarButtonItemStylePlain target:self action:@selector(leftAction:)];
    
    UIScrollView *bigBGV = [[UIScrollView alloc]initWithFrame:CGRectMake(0, self.navigationController.navigationBar.frame.size.height+[UIApplication sharedApplication].statusBarFrame.size.height, SCREENWIDTH, SCREENHEIGHT-kTabBarHeight-self.navigationController.navigationBar.frame.size.height-[UIApplication sharedApplication].statusBarFrame.size.height-20)];
    bigBGV.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bigBGV];
    self.bigBGV = bigBGV;
    
    NSArray *titleArr = self.dataDic[@"warehouseInfs"];
    int x;
    int y;
    int w = 130;
    int h = 80;
    int xcon = (bigBGV.frame.size.width-w*2)/3;
    int ycon = 30;
    for (int i=0; i<titleArr.count; i++) {
        x = i%2*(xcon+w)+xcon;
        y = i/2*(ycon+h)+ycon;
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.layer.borderWidth = 3;
        btn.layer.borderColor = RGBCOLOR(108, 185, 252).CGColor;
        btn.backgroundColor = RGBCOLOR(108, 185, 252);
        btn.frame = CGRectMake(x, y, w, h);
        [btn setTitle:[NSString stringWithFormat:@"%@",titleArr[i][@"Warehouse"]] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        btn.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
        btn.layer.cornerRadius = 5;
        [bigBGV addSubview:btn];
        [btn addTarget:self action:@selector(dhAction:) forControlEvents:UIControlEventTouchUpInside];
        if (i==titleArr.count-1) {
            bigBGV.contentSize = CGSizeMake(bigBGV.frame.size.width, CGRectGetMaxY(btn.frame));
        }
    }
    
    if ([[NSString stringWithFormat:@"%@",self.dataDic[@"IsReview"]] boolValue] == YES) {
        UIView *bottomBGV = [[UIView alloc]initWithFrame:CGRectMake(0, SCREENHEIGHT-kTabBarHeight-20, SCREENWIDTH, kTabBarHeight+20)];
        bottomBGV.backgroundColor = RGBCOLOR(234, 234, 234);
        [self.view addSubview:bottomBGV];
        UIButton *lsddBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        lsddBtn.frame = CGRectMake(10, 15, 90, 40);
        lsddBtn.layer.cornerRadius = 5;
        lsddBtn.layer.borderWidth = 1;
        lsddBtn.layer.borderColor = RGBCOLOR(108, 185, 252).CGColor;
        lsddBtn.backgroundColor = RGBCOLOR(108, 185, 252);
        [lsddBtn setTitle:@"历史订单" forState:UIControlStateNormal];
        [lsddBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [bottomBGV addSubview:lsddBtn];
        [lsddBtn addTarget:self action:@selector(lsddBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        UIButton *ksdhBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        ksdhBtn.frame = CGRectMake(CGRectGetMaxX(lsddBtn.frame)+10, 15, bottomBGV.frame.size.width-lsddBtn.frame.size.width-CGRectGetMaxX(lsddBtn.frame)-30, 40);
        ksdhBtn.layer.cornerRadius = 5;
        ksdhBtn.layer.borderWidth = 1;
        ksdhBtn.layer.borderColor = RGBCOLOR(108, 185, 252).CGColor;
        ksdhBtn.backgroundColor = RGBCOLOR(108, 185, 252);
        [ksdhBtn setTitle:@"开始订货" forState:UIControlStateNormal];
        [ksdhBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [bottomBGV addSubview:ksdhBtn];
        [ksdhBtn addTarget:self action:@selector(ksdhBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        UIButton *shddBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        shddBtn.frame = CGRectMake(CGRectGetMaxX(ksdhBtn.frame)+10, 15, lsddBtn.frame.size.width, 40);
        shddBtn.layer.cornerRadius = 5;
        shddBtn.layer.borderWidth = 1;
        shddBtn.layer.borderColor = RGBCOLOR(108, 185, 252).CGColor;
        shddBtn.backgroundColor = RGBCOLOR(108, 185, 252);
        [shddBtn setTitle:@"审核订单" forState:UIControlStateNormal];
        [shddBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [bottomBGV addSubview:shddBtn];
        [shddBtn addTarget:self action:@selector(shddBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }else{
        UIView *bottomBGV = [[UIView alloc]initWithFrame:CGRectMake(0, SCREENHEIGHT-kTabBarHeight-20, SCREENWIDTH, kTabBarHeight+20)];
        bottomBGV.backgroundColor = RGBCOLOR(234, 234, 234);
        [self.view addSubview:bottomBGV];
        UIButton *lsddBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        lsddBtn.frame = CGRectMake(10, 15, 150, 40);
        lsddBtn.layer.cornerRadius = 5;
        lsddBtn.layer.borderWidth = 1;
        lsddBtn.layer.borderColor = RGBCOLOR(108, 185, 252).CGColor;
        lsddBtn.backgroundColor = RGBCOLOR(108, 185, 252);
        [lsddBtn setTitle:@"历史订单" forState:UIControlStateNormal];
        [lsddBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [bottomBGV addSubview:lsddBtn];
        [lsddBtn addTarget:self action:@selector(lsddBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        UIButton *ksdhBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        ksdhBtn.frame = CGRectMake(CGRectGetMaxX(lsddBtn.frame)+10, 15, bottomBGV.frame.size.width-CGRectGetMaxX(lsddBtn.frame)-20, 40);
        ksdhBtn.layer.cornerRadius = 5;
        ksdhBtn.layer.borderWidth = 1;
        ksdhBtn.layer.borderColor = RGBCOLOR(108, 185, 252).CGColor;
        ksdhBtn.backgroundColor = RGBCOLOR(108, 185, 252);
        [ksdhBtn setTitle:@"开始订货" forState:UIControlStateNormal];
        [ksdhBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [bottomBGV addSubview:ksdhBtn];
        [ksdhBtn addTarget:self action:@selector(ksdhBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    
    [self readPlist];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(delectPlist) name:@"xiadanle" object:nil];
    
}
-(void)shddBtnAction:(UIButton *)btn{//审核订单
    ReviewOfTheOrderViewController *roVC = [[ReviewOfTheOrderViewController alloc]init];
    roVC.userData = self.dataDic;
    [self.navigationController pushViewController:roVC animated:YES];
}
-(void)delectPlist{
    //清除plist文件，可以根据我上面讲的方式进去本地查看plist文件是否被清除
    NSFileManager *fileMger = [NSFileManager defaultManager];
    NSString *xiaoXiPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"myPlist.plist"];
    //如果文件路径存在的话
    BOOL bRet = [fileMger fileExistsAtPath:xiaoXiPath];
    if (bRet) {
        NSError *err;
        [fileMger removeItemAtPath:xiaoXiPath error:&err];
    }
}
//2.读取plist文件
 
-(void)readPlist{
   
    //第一种情况：读取本地存储的plist文件
    NSString *filePath = [NSHomeDirectory() stringByAppendingString:@"/Documents/myPlist.plist"];//要读取的plist文件的本地路径

    NSDictionary *dic1 = [NSDictionary dictionaryWithContentsOfFile:filePath];
    
    if (dic1) {
        for (UIButton *b in self.bigBGV.subviews) {
            if ([b.titleLabel.text isEqualToString:[NSString stringWithFormat:@"%@",dic1[@"ckHouse"][@"Warehouse"]]]) {
                self.lastBtn = b;
                self.lastBtn.layer.borderColor = RGBCOLOR(108, 185, 252).CGColor;
                self.lastBtn.selected = NO;
                break;
            }
        }
        self.dataDic = dic1[@"userData"];
        self.houseDic = dic1[@"ckHouse"];
        self.numdataArr = dic1[@"numDataMarr"];
        [self ksdhBtnAction:nil];
    }
 
}
#pragma mark 抖动
- (void)shakeView:(UIView*)viewToShake
{
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    CGFloat t =4.0;
    CGAffineTransform translateRight  =CGAffineTransformTranslate(CGAffineTransformIdentity, t,0.0);
    CGAffineTransform translateLeft =CGAffineTransformTranslate(CGAffineTransformIdentity,-t,0.0);
    viewToShake.transform = translateLeft;
    [UIView animateWithDuration:0.07 delay:0.0 options:UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeat animations:^{
        [UIView setAnimationRepeatCount:2.0];
        viewToShake.transform = translateRight;
    } completion:^(BOOL finished){
        if(finished){
            [UIView animateWithDuration:0.05 delay:0.0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
                viewToShake.transform =CGAffineTransformIdentity;
            } completion:NULL];
        }
    }];
}
-(void)dhAction:(UIButton *)btn{
    [self shakeView:btn];
    self.lastBtn.layer.borderColor = RGBCOLOR(108, 185, 252).CGColor;
    self.lastBtn.selected = NO;
    btn.selected = YES;
    btn.layer.borderColor = [UIColor redColor].CGColor;
    self.lastBtn = btn;
    NSArray *aaaa = self.dataDic[@"warehouseInfs"];
    for (int i=0; i<aaaa.count; i++) {
        if ([[NSString stringWithFormat:@"%@",aaaa[i][@"Warehouse"]] isEqualToString:btn.titleLabel.text]) {
            self.houseDic = aaaa[i];
            break;
        }
    }
}
-(void)lsddBtnAction:(UIButton *)btn{
    //跳转历史订单
    OrderHistoryViewController *ohVC = [[OrderHistoryViewController alloc]init];
    ohVC.userData = self.dataDic;
    ohVC.ckHouse = self.houseDic;
    [self.navigationController pushViewController:ohVC animated:YES];
}
-(void)ksdhBtnAction:(UIButton *)btn{
    if (self.lastBtn == nil) {
        [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
        [SVProgressHUD setMinimumDismissTimeInterval:0.2f];
        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"请选择仓库"];
        return;
    }
    //开始订货
    MaterialViewController *mVC = [[MaterialViewController alloc]init];
    mVC.title = self.lastBtn.titleLabel.text;
    mVC.userData = self.dataDic;
    mVC.ckHouse = self.houseDic;
    mVC.neeeNumDataMarr = self.numdataArr?self.numdataArr:nil;
    [self.navigationController pushViewController:mVC animated:YES];
}
-(void)rightAction:(UIButton *)btn{//退出登录
    NSString *str = [[NSUserDefaults standardUserDefaults] objectForKey:@"ipaddress"];
    if (str.length == 0) {
        // 请求头
//        NSString *accessPath = @"http://192.168.0.19:80/Api/OrderGoods/UserLogout";
        NSString *accessPath = @"http://crm.zhenyea.com/Api/OrderGoods/UserLogout";
        // 请求参数字典
        NSDictionary *params = @{
            @"strUser":[NSString stringWithFormat:@"%@",self.dataDic[@"UserID"]],
            @"strPassword":self.dataDicPass,
            @"strIMEI":[FCUUID uuidForVendor],
            @"strEquipmentInf":@"苹果"
        };
        
        //创建配置信息
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        //设置请求超时时间：5秒
        configuration.timeoutIntervalForRequest = 5;
        //创建会话
        NSURLSession *session = [NSURLSession sessionWithConfiguration: configuration delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
        NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",accessPath]]];
        //设置请求方式：POST
        [request setHTTPMethod:@"POST"];
        [request setValue:@"application/json" forHTTPHeaderField:@"content-Type"];
        [request setValue:@"application/json;charset=gb2312" forHTTPHeaderField:@"Accept"];
        
        //data的字典形式转化为data
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil];
        //设置请求体
        [request setHTTPBody:jsonData];
        
        NSURLSessionDataTask * dataTask =[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            [SVProgressHUD dismiss];
            if (error == nil) {
                NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
                NSString *receiveStr = [[NSString alloc]initWithData:data encoding:encoding];
                NSData * aData = [receiveStr dataUsingEncoding:NSUTF8StringEncoding];
                NSError *errorr = nil;
                id response = [NSJSONSerialization JSONObjectWithData:aData options:NSJSONReadingMutableContainers error:&errorr];
                if ([response isKindOfClass:[NSDictionary class]]) {
                    // 请求成功数据处理
                    NSString *IsResult = [NSString stringWithFormat:@"%@",[response objectForKey:@"IsResult"]];
                    if ([IsResult isEqualToString:@"1"]) {
                        [self dismissViewControllerAnimated:YES completion:nil];
                    }else{
                        [SVProgressHUD setMinimumDismissTimeInterval:0.2f];
                        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:[NSString stringWithFormat:@"%@",response[@"Message"]]];
                    }
                } else {
                    [SVProgressHUD showWithStatus:[NSString stringWithFormat:@"%@",response[@"Message"]] maskType:SVProgressHUDMaskTypeClear];
                }
            }else{
                NSData * data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
                NSString * str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                NSLog(@"服务器的错误原因:%@",str);
                [SVProgressHUD dismiss];
            }
        }];
        [dataTask resume];

//        AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//        NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:accessPath parameters:params error:nil];
//        request.timeoutInterval = 10.f;
//        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
//
//        NSURLSessionDataTask *task = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
//            NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingUTF8);
//            NSString *receiveStr = [[NSString alloc]initWithData:responseObject encoding:encoding];
//            NSData * aData = [receiveStr dataUsingEncoding:NSUTF8StringEncoding];
//            NSError *errorr = nil;
//            id responsee = [NSJSONSerialization JSONObjectWithData:aData options:NSJSONReadingMutableContainers error:&errorr];
//            [SVProgressHUD dismiss];
//            if (!error) {
//                if ([responsee isKindOfClass:[NSDictionary class]]) {
//                    // 请求成功数据处理
//                    NSString *IsResult = [NSString stringWithFormat:@"%@",[responsee objectForKey:@"IsResult"]];
//                    if ([IsResult isEqualToString:@"1"]) {
//                        [self dismissViewControllerAnimated:YES completion:nil];
//                    }else{
//                        [SVProgressHUD setMinimumDismissTimeInterval:0.2f];
//                        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:[NSString stringWithFormat:@"%@",responsee[@"Message"]]];
//                    }
//                } else {
//
//                }
//            } else {
//                NSLog(@"请求失败error=%@", error);
//            }
//        }];
//
//        [task resume];
    }else{
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}
-(void)leftAction:(UIButton *)btn{//管理员
    
}
@end
